<template>
  <div class="register_container" v-loading="loading">
    <span class="register_title">新用户注册</span>
    <el-form ref="registerFormRef" label-width="120px" :rules="registerRules" :model="registerForm" status-icon
      class="register_form">
      <el-form-item label="登录账号" prop="account">
        <el-input v-model.trim="registerForm.account" />
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model.trim="registerForm.password"
            type="password" 
            autocomplete="off"
            show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model.trim="registerForm.confirmPassword" 
            type="password" 
            autocomplete="off" 
            show-password />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model.trim="registerForm.realName" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="registerForm.gender">
          <el-radio :label="Gender.MALE">男</el-radio>
          <el-radio :label="Gender.FEMALE">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="工作部门" prop="department">
        <el-input v-model.trim="registerForm.department" />
      </el-form-item>

      <el-form-item label="工号/学号" prop="employeeId">
        <el-input v-model.trim="registerForm.employeeId" />
      </el-form-item>

      <el-form-item label="手机号码" prop="phoneNo">
        <el-input v-model.trim="registerForm.phoneNo" />
      </el-form-item>

      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model.trim="registerForm.email" />
      </el-form-item>

      <el-form-item label="注册公用账号" prop="registerPublic">
        <el-checkbox 
                  v-model="registerForm.registerPublic"
                  :true-label="1"
                  :false-label="0"
                  @change="clickPublicRegister">
        </el-checkbox>
      </el-form-item>

      <el-form-item label="登录账号" prop="publicAccount" ref="publicAccountItem">
        <el-input v-model.trim="registerForm.publicAccount" 
                  :disabled="!registerForm.registerPublic"/>
      </el-form-item>

      <el-form-item label="登录密码" prop="publicPassword" ref="publicPasswordItem">
        <el-input v-model.trim="registerForm.publicPassword" 
                  type="password" 
                  autocomplete="off"
                  :disabled="!registerForm.registerPublic"
                  show-password />
      </el-form-item>
      <el-form-item label="确认登录密码" prop="confirmPublicPassword" ref="confirmPublicPasswordItem">
        <el-input v-model.trim="registerForm.confirmPublicPassword" 
                  type="password" 
                  autocomplete="off" 
                  :disabled="!registerForm.registerPublic"
                  show-password  />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitRegisterForm(registerFormRef)">
          注册
        </el-button>
        <el-button @click="resetRegisterForm(registerFormRef)">
          重置
        </el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup lang='ts' name='Register'>
  import { ref, reactive, toRaw } from 'vue';
  import { RegisterForm, Gender } from '@/types/type';
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
  import axios from "axios";

  const loading = ref(false)

  const registerForm = reactive<RegisterForm>({
    account: "",
    password: "",
    confirmPassword: "",
    realName: "",
    gender: Gender.MALE,
    department: "",
    employeeId: "",
    phoneNo: "",
    email: "",
    registerPublic: 1,
    publicAccount: "",
    publicPassword: "",
    confirmPublicPassword: "",
  })

  const registerFormRef = ref<FormInstance>()

  const validatePassword = (_: any, value: any, callback: any) => {
    if (value === '' || (value.length < 3 || value.length > 18)) {
      callback("请输入登录密码, 长度限于3到18位")
    } else {
      if (!registerFormRef.value) {
        return
      }
      if (registerForm.confirmPassword.length >= 3
          && registerForm.confirmPassword.length <= 18) {
        registerFormRef.value.validateField('confirmPassword')
      }
      callback()
    }
  }

  const checkPasswordAgain = (_: any, value: any, callback: any) => {
    if (registerForm.password === "") {
      callback("请先输入登录密码, 长度限于3到18位")
    } else {
      if (value === '') {
        callback("请再次确认登录密码")
      } else if (value !== registerForm.password) {
        callback("两次输入的密码不一致")
      } else {
        callback()
      }
    }
  }


  const validatePublicAccount = (_: any, value: any, callback: any) => {
    if (!registerForm.registerPublic) {
      callback()
      return
    }
    if (value === '' || value.length < 3 || value.length > 18) {
      callback("请输入登录账号, 长度限于3到18位")
    } else {
      callback()
    }
  } 

  const validatePublicPassword = (_: any, value: any, callback: any) => {
    if (!registerForm.registerPublic) {
      callback()
      return
    }
    if (value === '') {
      callback("请输入登录密码, 长度限于3到18位")
    } else {
      if (!registerFormRef.value) {
        return
      }
      if (registerForm.confirmPublicPassword.length >= 3
          && registerForm.confirmPublicPassword.length <= 18) {
        registerFormRef.value.validateField('confirmPublicPassword')
      }
      callback()
    }
  }

  const checkPublicPasswordAgain = (_: any, value: any, callback: any) => {
    if (!registerForm.registerPublic) {
      callback()
      return
    }
    if (registerForm.publicPassword === "") {
      callback("请先输入登录密码, 长度限于3到18位")
    } else {
      if (value === '') {
        callback("请再次确认登录密码")
      } else if (value !== registerForm.publicPassword) {
        callback("两次输入的密码不一致")
      } else {
        callback()
      }
    }
  }



  const registerRules = reactive<FormRules<RegisterForm>>({
    account: [
      {
        required: true,
        message: '请输入登录的账号, 长度限于3到18位',
        min: 3,
        max: 18,
        trigger: 'blur'
      },
    ],
    password: [
      {
        required: true,
        validator: validatePassword,
        trigger: 'blur',
      },
    ],
    confirmPassword: [
      {
        required: true,
        validator: checkPasswordAgain,
        trigger: "blur"
      }
    ],
    realName: [
      {
        required: true,
        min: 3,
        max: 18,
        message: '请输入您的真实姓名, 长度限于3到18位',
        trigger: 'blur'
      },
    ],
    gender: [
      {
        required: true,
        message: '请选择性别',
        trigger: 'change',
      },
    ],
    department: [
      {
        required: true,
        message: '请输入所在工作单位',
        trigger: 'blur',
      },
    ],
    employeeId: [
      {
        required: true,
        pattern: /^2[0-9]{4,}$/,
        message: '请输入以数字2开头, 且长度大于等于5位的有效工号或学号',
        trigger: 'blur'
      },
    ],
    phoneNo: [
      {
        required: true,
        pattern: /^1[3456789][0-9]{9}$/,
        len: 11,
        message: '请输入一个长度等于11位有效的手机号码',
        trigger: 'blur',
      },
  ],
    email: [
      {
        required: true,
        max: 24,
        message: '请输入长度不大于24的邮箱地址',
        trigger: 'blur',
      },
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: 'blur',
      },
  ],

    // 是否同时注册公共账号
    registerPublic: [
      {
        required: true,
        message: '请选择是否同时注册公共账号',
        trigger: 'change',
      },
    ],

    publicAccount: [
    { 
        required: registerForm.registerPublic === 1,
        validator: validatePublicAccount,
        message: "请输入登录账号, 长度限于3到18位",
        trigger: 'blur'
      },
    ],
    publicPassword: [
      {
        required: registerForm.registerPublic === 1,
        validator: validatePublicPassword,
        message: "请输入登录密码, 长度限于3到18位",
        trigger: 'blur',
      }
    ],
    confirmPublicPassword: [
      {
        required: registerForm.registerPublic === 1,
        validator: checkPublicPasswordAgain,
        message: "请确认登录密码, 长度限于3到18位",
        trigger: "blur"
      }
    ]
  })

  const submitRegisterForm = async (formElement: FormInstance | undefined) => {
    if (!formElement) {
      return
    }
    await formElement.validate((valid, fields) => {
      if (valid) {
        loading.value = true
        const register = axios.create({
          baseURL: "/api",
          headers: {
            "ContentType": "application/json;charset=UTF-8",
          },
          timeout: 5000,
        })
        // 以JSON数据格式, 提交新用户注册信息
        register.post("/register", toRaw(registerForm)).then((res: any)=> {
          loading.value = false
          const { message, resCode, data } = res.data
          console.log("message=" + message + ", resCode=" + resCode + ", data=" + data)
          ElMessage({
            message: message,
            type: data ? 'success' : 'error',
          })
        }).catch((reason: any)=> {
          loading.value = false
          ElMessage({
            message: '注册失败',
            type: 'error',
          })
          console.log(reason);
        })
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const resetRegisterForm = (formElement: FormInstance | undefined) => {
    if (!formElement) {
      return
    }
    formElement.resetFields()
  }

  const publicAccountItem =  ref()
  const publicPasswordItem =  ref()
  const confirmPublicPasswordItem =  ref()

  const clickPublicRegister = (registerPublic: boolean) => {
    if (!registerPublic) {
      publicAccountItem.value.resetField()
      publicPasswordItem.value.resetField()
      confirmPublicPasswordItem.value.resetField()

    }
  }

</script>

<style scoped lang='scss'>
  .register_container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .register_title {
      font-size: 24px;
      font-weight: bold;
      margin-top: 40px;
      margin-bottom: 20px;
    }

    .register_form {
      width: 60%;
    }
  }

  .el-input {
    --el-input-focus-border-color: purple;
  }
</style>